package com.example.fan.airline_reservation;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.ShapeBadgeItem;
import com.example.fan.airline_reservation.Custom.CreateUserDialog;
import com.example.fan.airline_reservation.Model.Fight;
import com.example.fan.airline_reservation.Model.USER;
import com.example.fan.airline_reservation.fragment_class.ac_add_fights;
import com.example.fan.airline_reservation.fragment_class.ac_statistic;
import com.example.fan.airline_reservation.fragment_class.traveler_search;
import com.example.fan.airline_reservation.fragment_class.traveler_trip;

import org.w3c.dom.Text;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;

public class Traveler_Interface extends AppCompatActivity {

    USER user;
    Bundle bundle=new Bundle();
    DrawerLayout drawer;
    LinearLayout right;
    NavigationView left;

    private LocalReceiver localReceiver;
    private IntentFilter intentFilter;
    private LocalBroadcastManager localBroadcastManager;

    private CreateUserDialog createUserDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traveler__interface);
        Intent intent=getIntent();
        user=(USER)getIntent().getSerializableExtra("USER11");
        bundle.putSerializable("USER11",user);
        /*隐藏title*/
        /*getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }

        Bmob.initialize(this, "0802cbf346296dc9fac5a477f911ba39");

        /*底部导航栏相关操作！！！！！*/
        BottomNavigationBar mBottomNavigationBar= (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        mBottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED)
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);

        mBottomNavigationBar
                .setActiveColor(R.color.black)//选中颜色 图标和文字
//                .setInActiveColor("#8e8e8e")//默认未选择颜色
                .setBarBackgroundColor(R.color.white);//默认背景色
        ShapeBadgeItem mShapeBadgeItem = new ShapeBadgeItem()
                .setShapeColorResource(R.color.lawngreen)
                .setGravity(Gravity.TOP | Gravity.END)
                .setHideOnSelect(false);
        mBottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.home,"查询航班")
                        .setInactiveIcon(ContextCompat.getDrawable(Traveler_Interface.this,R.drawable.home))
                        .setBadgeItem(mShapeBadgeItem))
                .addItem(new BottomNavigationItem(R.drawable.home,"行程")
                        .setInactiveIcon(ContextCompat.getDrawable(Traveler_Interface.this,R.drawable.home)))
                /*.addItem(new BottomNavigationItem(R.drawable.me,"我的")
                        .setInactiveIcon(ContextCompat.getDrawable(Traveler_Interface.this,R.drawable.me)))*/
                .setFirstSelectedPosition(0)//设置默认选择的按钮
                .initialise();//所有的设置需在调用该方法前完成
        replaceFragment(0);//默认选择第一个
        /*底部导航栏监听*/
        mBottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override/*选中切换*/
            public void onTabSelected(int position) {
                replaceFragment(position);
            }

            @Override/*上一次选中，我不做任何处理*/
            public void onTabUnselected(int position) {

            }

            @Override/*重复选中同一个，我也不做处理*/
            public void onTabReselected(int position) {

            }
        });


        /*滑动菜单部分*/
        left=(NavigationView)findViewById(R.id.left);
        /*left.setCheckedItem(R.id.recharge);*/
        left.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.recharge:
                        showEditDialog(getWindow().getDecorView().findViewById(R.id.content));
                        break;
                    case R.id.expect:
                        ToastShow("功能暂未上线，敬请期待");
                        drawer.closeDrawers();
                        break;
                }
                return true;
            }
        });
        right=(LinearLayout)findViewById(R.id.right);
        drawer=(DrawerLayout)findViewById(R.id.drawer);
        drawer.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {
                //获取屏幕的宽高
                WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                Display display = manager.getDefaultDisplay();
                //设置右面的布局位置  根据左面菜单的right作为右面布局的left
                //  左面的right+屏幕的宽度（或者right的宽度这里是相等的）为右面布局的right
                right.layout(left.getRight(), 0, left.getRight() + display.getWidth(), display.getHeight());
                if(left.getHeaderCount() > 0) {
                    View header = left.getHeaderView(0);
                    TextView name = (TextView) header.findViewById(R.id.navUserName);
                    name.setText(user.getName());
                    TextView B = (TextView) header.findViewById(R.id.navBalance);
                    B.setText("账户余额:¥"+user.getMoney());
                }
            }
            /*下面三个都没啥用*/
            @Override
            public void onDrawerOpened(@NonNull View view) {
            }
            @Override
            public void onDrawerClosed(@NonNull View view) {
            }
            @Override
            public void onDrawerStateChanged(int i) {
            }
        });

        /*广播监听器*/
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.fan.airline_reservation.LOCAL");
        localReceiver = new LocalReceiver();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);

    }

    private void replaceFragment(int position){
        Fragment fragment=null;
        switch (position){
            case 0:
                fragment=new traveler_search();
                fragment.setArguments(bundle);
                break;
            case 1:
                fragment=new traveler_trip();
                fragment.setArguments(bundle);
                break;
            /*case 2:
                fragment=new ac_add_fights();
                break;*/
            default:
                break;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.traveler_fragment,fragment);
        transaction.commit();
    }

    public void ToastShow(String message){
        Toast.makeText(Traveler_Interface.this,message,Toast.LENGTH_SHORT).show();
    }

    class LocalReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            user=(USER)intent.getSerializableExtra("newInfo");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

    public void showEditDialog(View view) {
        createUserDialog = new CreateUserDialog(this,
                R.style.MyDialog,onClickListener);
        createUserDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        createUserDialog.setCanceledOnTouchOutside(true);
        createUserDialog.show();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.next:
                    double m = Double.parseDouble(createUserDialog.getMoney().getText().toString());
                    user.setMoney(m+user.getMoney());
                    USER u = new USER(user.getName(),user.getPassword(),user.getType());
                    u.setMoney(user.getMoney());
                    u.update(user.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e==null){
                                ToastShow("充值成功");
                                drawer.closeDrawers();
                                createUserDialog.cancel();
                            }else {
                                ToastShow("充值失败，请重试");
                            }
                        }
                    });
                    break;
            }
        }
    };
}
